package com.bw.zg2.view.adapter

import android.content.Context
import android.widget.CheckBox
import android.widget.ImageView
import android.widget.TextView
import com.blankj.utilcode.util.ToastUtils
import com.bumptech.glide.Glide
import com.bw.zg2.R
import com.bw.zg2.bean.CartBean
import com.zhy.adapter.recyclerview.CommonAdapter
import com.zhy.adapter.recyclerview.base.ViewHolder
import org.greenrobot.eventbus.EventBus

/**
 *
 * @ClassName: HomeGoodsAdapter
 * @Description: java类作用描述
 * @Author: zhangyanchao
 * @CreateDate: 2024/9/19 8:42 AM
 * @Version: 1.0
 */
class CartGoodsAdapter(context: Context?, layoutId: Int, data: MutableList<CartBean>) :
    CommonAdapter<CartBean>(context, layoutId, data) {
    override fun convert(holder: ViewHolder?, t: CartBean?, position: Int) {
        holder?.setText(R.id.item_tv_desc, t?.goods_desc)
        holder?.setText(R.id.item_tv_price, "¥${t?.goods_default_price}")
        val img = holder?.getView<ImageView>(R.id.item_iv)
        img?.let { Glide.with(mContext).load(t?.goods_default_icon).into(it) }
        val checkBox = holder?.getView<CheckBox>(R.id.item_checkbox)

        //给checkBox 设置选中状态
        checkBox?.isChecked = t!!.check

        //处理商品选中事件
        checkBox?.setOnClickListener {
            //是否选中，true ,false
            t?.check = checkBox.isChecked
            //发送消息，通知页面选中效果
            EventBus.getDefault().post("cart")


        }

        val tvCount = holder?.getView<TextView>(R.id.tv_count)
        var count = t!!.count
        tvCount?.text = count.toString()

        //加
        holder?.getView<TextView>(R.id.tv_add)?.setOnClickListener {
            count++
            //给选中的商品数量赋值
            t?.count = count
            tvCount?.text = count.toString()

            EventBus.getDefault().post("cart")
        }
        //减
        holder?.getView<TextView>(R.id.tv_plus)?.setOnClickListener {
            count--
            if (count < 1) {
                ToastUtils.showShort("商品数量不能小于1")
                return@setOnClickListener
            }
            t?.count = count
            tvCount?.text = count.toString()

            EventBus.getDefault().post("cart")
        }
    }
}